<template>
  <BasicModal
    @register="registerModal"
    @cancel="onClose"
    destroyOnClose
    title="合并转账"
    :showCancelBtn="false"
    :showOkBtn="false"
    :canFullscreen="false"
    :centered="true"
    :width="'90%'"
    :bodyStyle="{ height: 'calc(100vh - 100px)', padding: '3px', overflowY: 'auto' }"
    :loading="loading"
    loadingTip="请稍候，后台努力处理中..."
  >
  <div style="zoom: 1; min-width:1200px; padding: 0 10px 10px; margin-top: 10px;" :style="{height:'calc(100vh - 150px)', overflowY:'auto'}">
    <table class="orderTable orderTableAlign" id="orderTable">
      <thead>
        <tr>
          <th colspan="10" align="left">审核信息</th>
        </tr>
      </thead>
      <tbody>
        <tr class="h-35px">
          <th width="6%">编号</th>
          <td width="14%"><span id="_id">{{ bean.id }}</span></td>
          <th width="6%">单号</th>
          <td width="14%"><span id="_lsh">{{ bean.orderId }}</span></td>
          <th width="6%">收入</th>
          <td width="14%"><span id="_skje" class="text-red-500" style="font-weight: bold; float: right">{{ toNumber(bean.skje) }}</span></td>
          <th width="6%">提交人</th>
          <td width="14%"><span id="_lrr">{{ bean.lrr }}</span></td>
          <th width="6%">提交时间</th>
          <td width="14%"><span id="_lrsj">{{ bean.lrsj }}</span></td>
        </tr>
        <tr class="h-35px">
          <th>收款银行</th>
          <td><span id="_djm">{{ bean.djm }}</span></td>
          <th>收付时间</th>
          <td><span id="_sksj">{{ bean.sksj }}</span></td>
          <th>支出</th>
          <td><span id="_fkje" class="text-green-500" style="font-weight: bold; float: right">{{ toNumber(bean.fkje) }}</span></td>
          <th>经理审核</th>
          <td><span id="_shr">{{ bean.shrName }}</span></td>
          <th>审核时间</th>
          <td><span id="_shsj">{{ bean.shsj }}</span></td>
        </tr>
        <tr class="h-35px" v-if="bean.sflx == '1' && bean.sffs == '3'">
          <th class="tdRight">入账银行</th>
          <td class="tdLeft"><span id="_djmPid">{{ bean.djmPid }}</span></td>
          <th class="tdRight"></th>
          <td class="tdLeft"><span id="_bz"></span></td>
          <th class="tdRight">入账金额</th>
          <td class="tdLeft"><span id="_jePid" class="text-red-500" style="font-weight: bold; float: right">{{ toNumber(bean.jePid) }}</span></td>
          <th>财务审批</th>
          <td><span id="_spr">{{ bean.sprName }}</span></td>
          <th>审批时间</th>
          <td><span id="_spsj">{{ bean.spsj }}</span></td>
        </tr>
        <tr class="h-35px" v-else>
          <th class="tdRight">备注</th>
          <td class="tdLeft" colspan="5">
            <span id="_bz">{{ bean.bz }}</span>
          </td>
          <th>财务审批</th>
          <td><span id="_spr">{{ bean.sprName }}</span></td>
          <th>审批时间</th>
          <td><span id="_spsj">{{ bean.spsj }}</span></td>
        </tr>
      </tbody>
    </table>

    
    <div class="listtab1" id="con_menu_1">
      <table class="orderTable" id="acctable">
        <thead>
          <tr>
            <th colspan="13">
              <div>收付项目</div>
              <div id="status_div">
                <span> 第 <b id="_intIndexNum">{{ data.idIndex + 1 }}</b>/<b id="_intTotal">{{ data.listSize }}</b> 条 </span>&nbsp;
                <span> 审核条数:<b id="_intCheck">{{ data.intCheckValue }}</b>&nbsp;&nbsp; 
                  回退条数:<b id="_intDelete">{{ data.intDeleteValue }}</b>&nbsp;&nbsp;
                  <input type="hidden" id="_intCheckValue" value="0" />
                  <input type="hidden" id="_intDeleteValue" value="0" />
                </span>
                <span>类型: <b id="_intSflx" :class="bean.sflx == '2' ? 'text-green-500' : 'text-red-500'">{{ bean.intSflx }}</b>&nbsp;&nbsp;</span>
                <span>方式: <b id="_intSffs">{{ bean.intSffs }}</b>&nbsp;&nbsp;</span>
                <span>审核状态: <b id="_intStat" :style="{ color: statClass }">{{ bean.intStat }}</b>&nbsp;&nbsp;</span>
              </div>
              <div class=""></div>
              <div id="oprt_buttons" style="text-align: right">
                <a-button
                  type="primary"
                  color="error"
                  @click="handleDeleteRecord"
                  v-if="data.cwhtButtonShow"
                  :disabled="data.cwhtButtonDisable"
                  class="mr-10px">回退</a-button>
                <a-button type="primary" @click="getUpRecord" class="mr-10px"> 上一条 </a-button>
                <a-button type="primary" @click="getNextRecord" class="mr-10px"> 下一条 </a-button>
                <a-button type="primary" color="success" @click="flowPayModal" v-if="data.payfinaceShow" :disabled="data.payfinaceDisable">
                  支付
                </a-button>
                <a-button type="primary" color="success" @click="handleCollateRecord" v-if="data.cwshButtonShow" :disabled="data.cwshButtonDisable">
                  审核
                </a-button>
                <!--a-button type="primary" color="warning" @click="handleRollbackRecord" v-if="data.rollbackShow" :disabled="data.rollbackDisable" > 取消 </a-button-->
              </div>
            </th>
          </tr>
        </thead>
      </table>


      <table class="orderTable" id="acctable"> 
        <thead>
          <tr>
            <th colspan="14">
              <span class="float-left w-200px leading-30px">转账审核</span>
            </th>
          </tr>
        </thead>
        <tbody>
          <tr class="listBg">
            <th width="100">订单号</th>
            <th width="70">部门</th>
            <th width="280" class="tal">名称</th>
            <th width="100" class="tar">收入</th>
            <th width="100" class="tar">支出</th>
            <th>备注</th>
            <th width="70">提交人</th>
            <th width="100">提交日期</th>
            <th width="70">操作人</th>
            <th width="100">操作日期</th>
            <th width="40">状态</th>
          </tr>
        </tbody>
        <tbody v-for="(list, index) in accountFlowList.optionList" :key="index">
          <tr :class="index % 2 == 0 ? 'listBg' : 'cor'">
            <td class="payshoworder" v-if="bean.sflx == '2'" @click="businessAccountTable(list.businessId, list.id)">{{ list.orderId }}</td>
            <td class="tal" v-else>{{ list.orderId }}</td>
            <td class="text-left">{{ list.pathName }}</td>
            <td class="text-left">{{ list.pathName }}</td>
            <td class="text-red-500 text-right">{{ toNumber(list.skje) }}</td>
            <td class="text-green-500 text-right">{{ toNumber(list.fkje) }}</td>
            <td class="text-left">{{ list.bz }}</td>
            <td>{{ list.realname }}</td>
            <td>{{ list.lrsj }}</td>
            <td>{{ list.shrName }}</td>
            <td>{{ list.shsj }}</td>
            <td>{{ list.statZw }}</td> 
          </tr>
          <!-- @click="showTRclick(isshow)" -->
        </tbody>
        <tfoot>
          <tr>
            <td class="tips">小计</td>
            <td>&nbsp;</td>
            <td>&nbsp;</td>
            <td>&nbsp;</td>
            <td>&nbsp;</td>
            <td>&nbsp;</td>
            <td class="tips text-red-500 text-right font-600" id="sumskje">{{ accountList.sumskje }}</td>
            <td class="tips text-green-500 text-right font-600" id="sumfkje">{{ accountList.sumfkje }}</td>
            <td>&nbsp;</td>
            <td>&nbsp;</td>
            <td>&nbsp;</td>
          </tr>
        </tfoot>
      </table>

      <table class="orderTable" id="acctable">
        <thead>
          <tr>
            <th colspan="14">
              <span class="float-left w-200px leading-30px">收支项目</span>
            </th>
          </tr>
        </thead>
        <tbody>
        <tr class="listBg">
          <th width="52" class="tac">状态</th>
          <th width="52" class="tac">类型</th>
          <th width="52" class="tac">方式</th>
          <th width="260">收付名称</th>
          <th width="80" class="text-right">收入</th>
          <th width="80" class="text-right">支出</th>
          <th width="135">收支银行</th>
          <th width="90" class="tac">收付时间</th>
          <th width="65" class="tac">操作人</th>
          <th>备注</th>
          <th width="90" class="tac">审核时间</th>
          <th width="70" class="tac">审核人</th>
        </tr>
        </tbody>
        <tbody v-for="(list,index) in accountList.optionList" :key="index">
        <tr :class="[index % 2 == 0 ? 'listBg' : 'cor', oAccountId == list.id ? 'selected': '']" >
          <td :class="accStatClass(list.stat)">{{list.statZw}}</td>
          <td :class="list.sflx=='1'?'text-red-500':'text-green-500'">{{list.sflxZw}}</td>
          <td>{{list.sffsZw}}</td>
          <td class="text-left" :class="list.invoiceStat=='1'?'text-blue-500':''">{{list.sfmc}}</td>
          <td class="text-right text-red-500">{{list.skje}}</td>
          <td class="text-right text-green-500">{{list.fkje}}</td>
          <td class="text-left">{{list.bankdjm}}</td>
          <td>{{list.sfsj}}</td>
          <td>{{list.lrr}}</td>
          <td class="text-left">{{list.bz}}</td>
          <td>{{list.shsj}}</td>
          <td>{{list.shrName}}</td>
        </tr><!--  -->
        </tbody>
        <tfoot>
        <tr>
          <td>&nbsp;</td>
          <td class="tips">小计</td>
          <td>&nbsp;</td>
          <td>&nbsp;</td>
          <td class="tips text-left font-500 text-blue-600"><span v-if="accountList.sumtotal<=100">共 {{ accountList.sumtotal }} 条数据</span></td>
          <td class="tips text-right font-500 text-red-600" id="sumskje">{{accountList.sumskje}}</td>
          <td class="tips text-right font-500 text-green-600" id="sumfkje">{{accountList.sumfkje}}</td>
          <td>&nbsp;</td>
          <td>&nbsp;</td>
          <td>&nbsp;</td>
          <td>&nbsp;</td>
          <td>&nbsp;</td>
          <td>&nbsp;</td>
        </tr>
        </tfoot>
      </table>
    </div>

    <div class="listtab1" id="con_menu_2" v-if="data.bankRunnigShow">
      <table class="orderTable" id="brtable">
        <thead>
          <tr>
            <th colspan="14">
              <span class="float-left w-200px leading-30px">银行流水</span>
              <span class="float-right text-right w-220px mr-2">
                <a-button id="addButton" color="success" @click="handleBankRunningAdd"> 添加 </a-button>
              </span>
            </th>
          </tr>
        </thead>
        <tbody>
          <tr class="listBg">
            <th width="100">记账时间</th>
            <th width="150">收支账户</th>
            <th width="220">对方账户</th>
            <th width="220">对方户名</th>
            <th width="80">收入</th>
            <th width="80">支出</th>
            <th width="">备注</th>
          </tr>
        </tbody>
        <tbody v-for="(list, index) in bankRunningList.optionList" :key="index">
          <tr :class="[index % 2 == 0 ? 'listBg' : 'cor', data.bankRunningId == list.id ? 'selected' : '']" @click="selectBrTable(index, list.id)">
            <td>{{ list.jzsj }}</td>
            <td>{{ list.djm }}</td>
            <td>{{ list.dfzh }}</td>
            <td>{{ list.dfhm }}</td>
            <td class="text-red-500">{{ toNumber(list.srje) }}</td>
            <td class="text-green-500">{{ toNumber(list.zcje) }}</td>
            <td class="text-left">{{ list.bz }}</td>
            <td style="display: none">{{ list.id }}</td>
          </tr>
        </tbody>
        <!--tbody v-if="bankRunning.optionList && bankRunning.optionList.length == 0" >
        <tr><td colspan="7" class="text-red-500">请先录入银行流水信息中心！</td></tr>
        </tbody-->
      </table>
    </div>

    <!--分解流水 2024-03-03 qindl---->
    <div class="listtab1" id="con_menu_2" v-if="data.bankBalanceShow">
      <table class="orderTable" id="brfjtable">
        <thead>
          <tr>
            <th colspan="14">
              <span class="float-left w-200px leading-30px">分解流水</span>
              <span class="float-right leading-30px current-stat">
                <span>已分解：<label class="font-bold text-red-500 mr-6">{{toNumber(bankBalanceList.sumskje)}}</label></span>
                <span>未分解：<label class="font-bold text-green-500 mr-2">{{toNumber(bean.jePid - bankBalanceList.sumskje)}}</label></span>
              </span>
            </th>
          </tr>
        </thead>
        <tbody>
          <tr class="listBg">
            <th width="100">记账时间</th>
            <th width="150">收支账户</th>
            <th width="220">对方账户</th>
            <th width="220">对方户名</th>
            <th width="80">收入</th>
            <th width="80">支出</th>
            <th width="">备注</th>
            <th width="40">状态</th>
          </tr>
        </tbody>
        <tbody v-for="(list, index) in bankBalanceList.optionList" :key="index">
          <tr :class="[index % 2 == 0 ? 'listBg' : 'cor', data.bankRunningPid == list.id ? 'selected' : '']" >
            <td>{{ list.jzsj }}</td>
            <td>{{ list.djm }}</td>
            <td>{{ list.dfzh }}</td>
            <td>{{ list.dfhm }}</td>
            <td class="text-red-500">{{ toNumber(list.srje) }}</td>
            <td class="text-green-500">{{ toNumber(list.zcje) }}</td>
            <td class="text-left">{{ list.bz }}</td>
            <td>{{ list.shbj == '0' ? '未审' : '已审'}}</td> 
            <td style="display: none">{{ list.id }}</td>
          </tr>
        </tbody> 
        <!--tbody v-if="!bankBalanceList.hasOwnProperty('optionList')" >
          <tr><td colspan="7" class="text-red-500">未有分解数据！</td></tr>
        </tbody-->
      </table>
    </div>
    <!------>

    <div class="listtab1" id="con_menu_3" v-if="data.accountTableShow">
      <table class="orderTable" id="accounttable">
        <thead><tr> <th colspan="12"> 收付项目 </th> </tr></thead>
        <tbody>
          <tr class="listBg">
            <th width="60">状态</th>
            <th width="60">类型</th>
            <th width="70">支付方式</th>
            <th width="260">收付名称</th>
            <th width="80">收入</th>
            <th width="80">支出</th>
            <th width="80">收支银行</th>
            <th width="100">收付时间</th>
            <th width="90">操作人</th>
            <th>备注</th>
            <th width="100">审核时间</th>
            <th width="70">审核人</th>
          </tr>
        </tbody>
        <tbody v-for="(list, index) in businessAccountList.optionList" :key="index">
          <tr :class="index % 2 == 0 ? 'listBg' : 'cor'">
            <td :class="list.stat == 3 ? 'text-red-500' : ''">{{ list.statZw }}</td>
            <td>{{ list.sflxZw }}</td>
            <td :class="list.sffs == 3 ? 'text-red-500' : ''">{{ list.sffsZw }}</td>
            <td class="text-left">{{ list.sfmc }}</td>
            <td class="text-right text-red-500">{{ toNumber(list.skje) }}</td>
            <td class="text-right text-green-500">{{ toNumber(list.fkje) }}</td>
            <td>{{ list.bankdjm }}</td>
            <td>{{ list.sfsj }}</td>
            <td>{{ list.lrr }}</td>
            <td class="text-left">{{ list.bz }}</td>
            <td>{{ list.shsj }}</td>
            <td>{{ list.shrName }}</td>
          </tr>
        </tbody>
        <tfoot>
          <tr>
            <td>&nbsp;</td>
            <td class="tips">小计</td>
            <td>&nbsp;</td>
            <td>&nbsp;</td>
            <td class="tips align--right fwb text-red-500">{{ toNumber(businessAccountList.sumskje) }}</td>
            <td class="tips align--right fwb text-green-500">{{ (businessAccountList.sumfkje) }}</td>
            <td>&nbsp;</td>
            <td>&nbsp;</td>
            <td>&nbsp;</td>
            <td>&nbsp;</td>
            <td>&nbsp;</td>
            <td>&nbsp;</td>
          </tr>
        </tfoot>
      </table>
    </div>
    </div>
  </BasicModal>
  <!--https://segmentfault.com/a/1190000039951044?utm_source=sf-similar-article @ok="bankRunningOk" @ok="flowPayOk"-->
  <AccountFlowPayModal @register="registerAccountFlowPay" @success="flowPayFinaceOk"></AccountFlowPayModal>
  <BankRunningModal @register="registerBankRunning" @success="bankRunningOk"></BankRunningModal>
  <BusinessOrder @register="registerBusinessOrder"></BusinessOrder>

</template>
<script lang="ts" setup>
  import '/@/design/order.css';
  import { ref, computed, unref, onMounted, reactive } from 'vue';
  import { BasicModal, useModal, useModalInner } from '/@/components/Modal';
  import {
    // getRecordById,
    // audit,
    // loadAccount,
    collateRecordJson,
    deleteRecordJson,
    rollbackRecord,
    loadBankRunning,
    loadBankBalance,
  } from '../types/accountflow.api';
  import {
    getRecordById,
    audit,
    loadAccountFlow,
  } from '../types/accountBatch.api';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { filterObj } from '/@/utils/common/compUtils';
  import { isEmpty } from '@/utils/is';

  import AButton from '/@/components/Button/src/BasicButton.vue';
  import AccountFlowPayModal from './AccountFlowPayModal.vue';
  import BankRunningModal from '/@/views/full/bank/modules/BankRunningModal.vue';
  import BusinessOrder from '/@/views/full/business/BusinessOrder.vue';
  import moment from 'dayjs';
  

  /**
   * 1、提交信息
   * 2、收支明细
   * 3、银行流水
   * 4、按钮显示
   * 5、按钮操作
   */
  const { createMessage: $message } = useMessage();
  // 声明Emits
  const emit = defineEmits(['success', 'register']);

  let bean = reactive<any>({}); //业务信息
  let accountFlowList = reactive<any>({}); //业务信息
  let accountList = reactive<any>({}); //业务收支明细
  let businessAccountList = reactive<any>({}); //订单收支明细
  let bankRunningList = reactive<any>({}); //银行流水
  let bankBalanceList = reactive<any>({}); //分解流水
  let isReload = ref(false); //是否有数据操作
  let loading  = ref(true); //
  let oAccountId = ref('');

  //界面控制数据
  let data = reactive({
    idArray: [], //数据数组
    idIndex: 0, //当前位置
    type: '', //业务类型
    stats: {}, //当前数据状态
    auditRecord: {}, //已审核数据
    listSize: 0, //数组总数
    intCheckValue: 0,
    intDeleteValue: 0,
    flowIds: '',
    accountId: '',
    bankRunningId: '',
    bankRunningPid: '',
    payfinaceDisable: false,  //支付
    cwshButtonDisable: true,  //审核
    cwshButtonShow: false,    //审核
    rollbackDisable: false,   //取消
    rollbackShow: false,      //取消
    cwhtButtonDisable: false, //回退
    cwhtButtonShow: true, //回退
    payfinaceShow: false, //支付
    bankRunnigShow: false, //银行流水
    bankBalanceShow: false, //分解流水
    accountTableShow: false, //收支明细
  });

  //界面控制数据
  let bankRunningForm = reactive<any>({
    bankId: '',
    sflx: '',
    jzsj: '',
    je: 0,
  });

  //银行分解数据
  let bankBalanceModel = reactive<any>({
    djm: '',
    jzsj: '',
    sflxZW: '',
    zje: 0,
    yfje: 0,
    wfje: 0,
  });

  const getTitle = computed(() => {
    let title = '';
    if (data.type == 'takeFinaneChecked') {
      title = '收款审核';
    } else if (data.type == 'payFinaneChecked') {
      title = '转账支付';
    } else if (data.type == 'takePayment') {
      title = '挂账支付';
    } else if (data.type == 'takePayment') {
      title = '经理审批';
    } else if (data.type == 'takeManageChecked') {
      title = '挂账审批';
    } else if (data.type == 'payManageChecked') {
      title = '转账审核';
    }
    return title;
  });

  //1未审、2经理、3已审、9回退
  const statClass = computed(() => {
    let color = '#666';
    if (data.stats['stat'] == '1') {
      color = '#10b981';
    } else if (data.stats['stat'] == '2') {
      color = '#ff0808';
    } else if (data.stats['stat'] == '3') {
      color = 'orangered';
    } else if (data.stats['stat'] == '9') {
      color = '#333';
    }
    return color;
  });

  //表单赋值
  const [registerModal, { closeModal }] = useModalInner(async (data) => {
    await init(data);
  });

  //TODO---------数据初始化--------------------------------------------------------------------
  function setIdArray(array) {
    data.idArray = array && array.split(',');
    if (array == null || array == '') {
      data.listSize = 0;
    } else {
      data.listSize = data.idArray?.length;
    }
  }

  function init(record) {
    if (!record.id) {
      $message.warning('订单编号不能为空!');
      return;
    }
    audit(filterObj(record)).then((res) => {
      try {
        if (res.success != true) {
          $message.warning(res.message);
          return false;
        }
        let result = res.result;
        setIdArray(result.idArray);
        data.type = result.type;
        data.idIndex = result.idIndex;
        getNextRecord();
      } catch (e) {
        $message.error('initData : ' + e);
        return false;
      }
    }).finally(() => {
      //data.loading = false
    });
  }

  //上一条
  function getUpRecord() {
    //$(':button').attr('disabled', 'true')
    var indexNum = data.idIndex;
    if (indexNum == null) {
      $message.warning('上一条 -> 数据下标有误！');
      refreshBtn();
      return;
    } else if (indexNum == -1 || indexNum == 0) {
      $message.warning('已经是第一条数据');
      refreshBtn();
      return;
    }
    var id = data.idArray[indexNum - 1];
    getRecordById({ id: id }).then((res) => {
      if (res.success) {
        let result = res.result;
        data.idIndex = indexNum - 1;
        setBean(result);
      } else {
        $message.warning(res.message);
      }
    }).catch((error) => {
      console.error(error);
    }).finally(() => {
      refreshBtn();
      loadAccountFlowList();
      loadAccoutList();
    });
  }

  //下一条
  function getNextRecord() {
    //$(":button").attr("disabled", true);
    var indexNum = data.idIndex; //下标
    if (data.listSize == 0) {
      $message.warning('数据已经审核完毕,未查询到下一条数据');
      //removeMask();
      return;
    }
    indexNum = Number(indexNum) + 1;
    if (indexNum >= data.listSize) {
      $message.warning('已经是最后一条数据');
      refreshBtn();
      //removeMask();
      return;
    }
    var id = data.idArray[indexNum];
    getRecordById({ id: id }).then((res) => {
      if (res.success) {
        let result = res.result;
        data.idIndex = indexNum;
        //$("#_intIndexNum").text(indexNum + 1);	// 设置显示当前条数
        //$("#_indexNum").attr("value", Number(indexNum));	// 设置当前数据下标数值
        setBean(result);
      } else {
        $message.warning(res.message);
      }
    })
    .catch((error) => {
      console.error(error);
    })
    .finally(() => {
      refreshBtn();
      loadAccountFlowList();
      loadAccoutList();
    });
  }

  async function setBean(jsonObj) {
    try {
      bean.id = jsonObj.id;
      bean.lsh = jsonObj.lsh;
      bean.orderId = jsonObj.orderId;
      bean.lrr = jsonObj.lrr;
      bean.lrsj = jsonObj.lrsj;
      bean.skje = jsonObj.skje;
      bean.fkje = jsonObj.fkje;
      bean.sksj = jsonObj.sksj;
      bean.djm = jsonObj.djm;
      bean.shrName = jsonObj.shrName;
      bean.shsj = jsonObj.shsj;
      bean.sprName = jsonObj.sprName;
      bean.spsj = jsonObj.spsj;
      bean.sflx = jsonObj.sflx;
      bean.backReason = jsonObj.backReason;

      data.stats['stat'] = jsonObj.stat;
      data.flowIds       = jsonObj.flowIds;
      data.accountId     = jsonObj.accountId;

      bean.intStat = jsonObj.statZw;
      bean.intSffs = jsonObj.sffsZw;
      bean.intSflx = jsonObj.sflxZw;

      //需要提交
      bean.bankId = jsonObj.bankId;
      bean.ywlx = jsonObj.sflx;
      bean.sffs = jsonObj.sffs;
      bean.br_sksj = jsonObj.sksj;

      //qindl 2024-03-02
      bean.djmPid = jsonObj.djmPid;
      bean.jePid = jsonObj.jePid;
      var bankId = jsonObj.bankId;
      var je = jsonObj.je;

      if (jsonObj.sflx == '1' && jsonObj.sffs == '3') {
        bankId = jsonObj.bankPid;
        je = jsonObj.jePid;
        //录入银行流水表单
        bankRunningForm.bankId = jsonObj.bankPid;
        bankRunningForm.sflx = jsonObj.sflx;
        bankRunningForm.je = jsonObj.jePid;
        bankRunningForm.jzsj = jsonObj.sksj;
        data.bankBalanceShow = true;
        //已审核银行流水
        data.bankRunningId = jsonObj.bankRunningPid;
        data.bankRunningPid = jsonObj.bankRunningId;
      } else {
        //录入银行流水表单
        bankRunningForm.bankId = jsonObj.bankId;
        bankRunningForm.sflx = jsonObj.sflx;
        bankRunningForm.je = jsonObj.je;
        bankRunningForm.jzsj = jsonObj.sksj;
        data.bankBalanceShow = false;
        //已审核银行流水
        data.bankRunningId = jsonObj.bankRunningId;
        data.bankRunningPid = jsonObj.bankRunningPid;
      }
      //------------------------------------
      
      //console.info("accountflowInterval@@@@", data.bankRunningId, data.bankRunningPid, (bean.ywlx == '1' && bean.sffs == '3'))
      if (bean.ywlx == '1' && bean.sffs == '3') {
        await loadBankRunnigList(jsonObj.bankRunningPid, bankId, jsonObj.sflx, jsonObj.sksj, je);
        console.info("loadBankRunnigList@@@11111", bankRunningList);
        let pid = jsonObj.bankRunningPid;
        if (jsonObj.stat != 3 && bankRunningList.optionList.length == 1) {
          //只有一条银行流水时，默认选中它
          pid = bankRunningList.optionList && bankRunningList.optionList[0].id;
          data.bankRunningId = pid;
        }
        console.info("loadBankRunnigList@@@222", bankRunningList.optionList[0].id)
        await loadBankBalanceList(pid);
      } else {
        loadBankRunnigList(jsonObj.bankRunningId, bankId, jsonObj.sflx, jsonObj.sksj, je);
      }
    } catch (e) {
      //alert("setBean -> " + e.message)
      return;
    }
  }

  /**
   * 2020-08-24 取消
   * 当收支项目走到，财务管理（收款审核、转账支付、挂账支付），财务需要回退重新操作
   */
  function handleRollbackRecord() {
    var indexNum = data.idIndex;
    if (indexNum == null) {
      $message.warning('请先选择收付待审核数据');
      refreshBtn();
      return;
    }
    var recheck = ''; //$("#_recheck").val();
    var type = data.type;
    var id = data.idArray[indexNum];
    var nextId = data.idArray[indexNum];

    var params = {
      id: id,
      nextId: nextId,
      recheck: recheck,
      type: type,
    };
    rollbackRecord(params)
      .then((res) => {
        //$message.warning(res.message)
        if (res.success == true) {
          var msg = res.result;
          if (msg != '') {
            data.idIndex = indexNum;
            setBean(msg);
          } else {
            refreshBtn();
            $message.warning('数据已经审核完毕,未查询到下一条数据');
          }
          if (typeof data.auditRecord['_' + id] == 'undefined') {
            // 未审核
            data.intCheckValue++;
          } else if (data.auditRecord['_' + id] == 1) {
            // 已通过
            data.intCheckValue--;
            data.intCheckValue++;
          }
          data.auditRecord['_' + id] = 0; // 标记为作废

          //2021-10-25 qindl
          $message.success(' 操作成功！');
        } else {
          $message.warning(res.message);
          return false;
        }
      })
      .finally(() => {
        refreshBtn();
        loadAccountFlowList();
        loadAccoutList();
        isReload.value = true;
      });
  }

  //根据ID加载操作日志 2\收付项目
  function loadAccountFlowList() {
    //清空
    Object.keys(accountFlowList).map((key) => delete accountFlowList[key]);
    var account_ids = data.flowIds;
    if (account_ids == '' || account_ids == null) {
      return false;
    }
    var params = { account_ids: account_ids };
    loadAccountFlow(params).then((res) => {
      if (res.success != true) {
        //this.$message.warning(res.message)
        return false;
      }
      Object.assign(accountFlowList, res.result);
    });
  }

  //根据ID加载操作日志 2\收付项目
  function loadAccoutList() {
    //清空
    Object.keys(accountList).map((key) => delete accountList[key]);
    var account_ids = data.accountId;
    if (account_ids == '' || account_ids == null) {
      return false;
    }
    var params = { account_ids: account_ids };
    loadAccountFlow(params).then((res) => {
      if (res.success != true) {
        //this.$message.warning(res.message)
        return false;
      }
      Object.assign(accountList, res.result);
    });
  }

  /**
   * 查看 订单详情
   * 作者：qdl
   * 日期：2023-05-23
   */
  //详细订单
  const [registerBusinessOrder, { openModal: openBusinessOrder }] = useModal();
  //双击行
  function handleDblclick(data) {
    openBusinessOrder(true, data);
  }

  //收款 ------------------------------------------------
  function businessAccountTable($orderId, $id) {
    //$("#con_menu_3").show();
    var params = { id: $orderId, oAccountId: $id, buttonAll: false };
    handleDblclick(params);
  }

  //点击选择银行流水
  function selectBrTable(index, id) {
    // 状态：3已审｜9回退 || data.stats['stat'] == 9
    if (data.stats['stat'] == 3) {
      console.info('当前状态不可以操作！' + data.stats['stat']);
      return;
    }

    // 选中流水编号
    if (!data.bankRunningId || data.bankRunningId != id) {
      data.bankRunningId = id;
      data.cwshButtonDisable = false;
    } else {
      data.bankRunningId = '';
      data.cwshButtonDisable = true;
    }
    
    let jsonObj = accountFlow;
    if (jsonObj.sflx == '1' && jsonObj.sffs == '3') {
        //需要提交
        bankRunningForm.bankId = jsonObj.bankPid;
        bankRunningForm.sflx = jsonObj.sflx;
        bankRunningForm.je = jsonObj.jePid;
        bankRunningForm.jzsj = jsonObj.sksj;
      } else {
        //需要提交
        bankRunningForm.bankId = jsonObj.bankId;
        bankRunningForm.sflx = jsonObj.sflx;
        bankRunningForm.je = jsonObj.je;
        bankRunningForm.jzsj = jsonObj.sksj;
      }

      loadBankBalanceList(data.bankRunningId);
      //------------------------------------
  }

  //TODO---------审核操作--------------------------------------------------------------------
  //通过 审核 + 支付
  function handleCollateRecord() {
    loading.value = true;
    if (data.stats['stat'] == 3) {
      $message.warning('该数据财务已审核!');
      refreshBtn();
      return;
    }
    //$(':button').attr('disabled', 'true') || indexNum === ''
    var indexNum = data.idIndex;
    if (indexNum == null) {
      $message.warning('请先选择审核信息');
      refreshBtn();
      return;
    }
    indexNum = Number(indexNum);

    var type = data.type;
    if (type == null || type == '') {
      $message.warning('TYPE值为空，数据异常请联系管理员');
      refreshBtn();
      return;
    }

    var bankRunningId = data.bankRunningId;
    if (type == 'takeFinaneChecked' && (bankRunningId == null || bankRunningId == '')) {
      $message.warning('收款审核，请先选择银行流水数据');
      refreshBtn();
      return;
    }

    var recheck = ''; //$('#_recheck').val() 不知道有什么用
    var id = data.idArray[indexNum];
    var nextId = data.idArray[indexNum];

    var params = {
      id: id,
      bankRunningId: bankRunningId || '',
      nextId: nextId,
      recheck: recheck,
      type: type,
      bankId: bankRunningForm.bankId,
      fkje: bankRunningForm.je,
      jzsj: bankRunningForm.jzsj,
      dfzh: bankRunningForm.dfzh,
      dfhm: bankRunningForm.dfhm,
    };

    collateRecordJson(params).then((res) => {
      if (res.success == true) {
        var msg = res.result;
        if (msg != '') {
          data.idIndex = indexNum;
          setBean(msg);
        } else {
          $message.warning('数据已经审核完毕,未查询到下一条数据');
        }
        // 未审核
        if (typeof data.auditRecord['_' + id] == 'undefined') {
          data.intCheckValue++;
        } else if (data.auditRecord['_' + id] == 1) {
          // 已通过
          data.intCheckValue--;
          data.intCheckValue++;
        }
        // 标记为作废
        data.auditRecord['_' + id] = 0;

        $message.success(' 操作成功！');
      } else {
        //this.$notification.warning({ message: res.message })
        $message.warning(res.message);
        return false;
      }
    }).finally(() => {
      refreshBtn();
      loadAccoutList();
      isReload.value = true;
    });
  }

  /**
   * 回退原因 提交触发
   * 作者：qdl
   * 日期：2023-02-23
   */
  const [registerAccountFlowBackReason, { openModal: accountFlowBackReasonModal }] = useModal();
  function handleBackReasonModal() {
    var indexNum = data.idIndex;
    if (indexNum == null) {
      $message.warning('请先选择收付待审核数据');
      refreshBtn();
      return;
    }
    accountFlowBackReasonModal();
  }

  //回退 - 确认
  function handleDeleteRecord() {
    //$(':button').attr('disabled', 'true')
    loading.value = true;
    var indexNum = data.idIndex;
    if (indexNum == null) {
      $message.warning('请先选择收付待审核数据');
      refreshBtn();
      return;
    }

    //var recheck = $('#_recheck').val()
    var recheck = '';
    var type = data.type;

    indexNum = Number(indexNum);
    var id = data.idArray[indexNum];
    var nextId = data.idArray[indexNum];

    var params = {
      id: id,
      nextId: nextId,
      recheck: recheck,
      type: type,
    };
    deleteRecordJson(params).then((res) => {
      if (res.success == true) {
        var msg = res.result;
        if (msg != '') {
          data.idIndex = indexNum;
          setBean(msg);
        } else {
          refreshBtn();
          $message.warning('数据已经审核完毕,未查询到下一条数据');
        }
        if (typeof data.auditRecord['_' + id] == 'undefined') {
          // 未审核
          data.intDeleteValue++;
        } else if (data.auditRecord['_' + id] == 1) {
          // 已通过
          data.intDeleteValue--;
          data.intDeleteValue++;
        }
        data.auditRecord['_' + id] = 0; // 标记为作废

        //2021-10-25 qindl
        $message.success(' 操作成功！');
      } else {
        $message.warning(res.message);
        return false;
      }
    }).finally(() => {
      refreshBtn();
      loadAccoutList();
      isReload.value = true;
    });
  }

  /**
   * 列表-银行流水
   * @param id 
   * @param sflx 收付类型
   * @param sffs 收付方式
   * @param jzsj 记账日期
   * @param bankId 记账银行
   * @param je 记账金额
   * @param bankPid 入账金额
   * @param jePid 入账金额
   */
  async function loadBankRunnigList(id, bankId, sflx, jzsj, je) {
    refreshBankRunningList();
    var type = data.type;
    if (type == 'takeFinaneChecked' || type == 'takeFinaneRechecked') {
      data.bankRunnigShow = true;
    } else {
      data.bankRunnigShow = false;
      return false;
    }
    if ((typeof bankId == 'undefined' || bankId == '') && (typeof jzsj == 'undefined' || jzsj == '')) {
      return false;
    }
    var params = {
      id: id,
      bankId: bankId,
      sflx: sflx,
      jzsj: jzsj,
      je: je,
    };
    await loadBankRunning(params).then((res) => {
      if (res.success != true) {
        $message.warning(res.message);
        return false;
      }
      Object.assign(bankRunningList, res.result);
      //console.info("bankRunningList@@", bankRunningList)
    });
  }

  /**
   * 列表-银行流水
   * @param id 
   */
  function loadBankBalanceList(id) {
    refreshBankBalanceList();
    if (typeof id == 'undefined' || id == '' || id == null) {
      return false;
    }
    var params = {
      id: id,
    };
    loadBankBalance(params).then((res) => {
      if (res.success != true) {
        $message.warning(res.message);
        return false;
      }
      Object.assign(bankBalanceList, res.result);
    });
  }

  /**
   * 刷新重置按钮
   * 1、按钮：审核 （转账审核：直接可用； 收款审核：需要点选银行流水）
   * 2、按钮：取消 （隐藏，只有转账支付、挂账支付，账务审核后才显示）
   * 3、银行流水： （转账支付才显示）
   * 4、收支明细： （转账支付，点订单编号才显示）
   */
  function refreshBtn() {
    var type = data.type;
    loading.value = false;
    data.rollbackShow = false; //撤销
    data.accountTableShow = false;
    if (type == 'viewData') {
      data.cwhtButtonDisable = false;
      data.cwshButtonDisable = true;
    } else if (type == 'payFinaneChecked' || type == 'takePayment') {
      //2、状态：2经理；3已审；9回退；payFinaneChecked（ 转账支付）、takePayment（挂账支付）
      data.payfinaceShow = true; //支付
      data.cwshButtonShow = false; //审核
      if (data.stats['stat'] == '3') {
        //3已审
        data.cwhtButtonDisable = false;
        data.payfinaceDisable = true;
        data.payfinaceShow = true; //支付
        data.rollbackShow = true; //撤销
      } else if (data.stats['stat'] == '9') {
        data.payfinaceDisable = true;
        data.cwhtButtonDisable = true;
      } else {
        data.payfinaceDisable = false;
        data.cwhtButtonDisable = false;
      }
    } else {
      //2、状态：2经理；3财务；9回退
      data.payfinaceShow = false;
      data.cwshButtonShow = true;
      if (data.stats['stat'] == '2' || data.stats['stat'] == '3') {
        data.cwhtButtonDisable = false;
        data.cwshButtonDisable = true;
      } else if (data.stats['stat'] == '9') {
        data.cwshButtonDisable = false;
        data.cwhtButtonDisable = true;
      } else {
        data.cwshButtonDisable = false;
        data.cwhtButtonDisable = false;
      }
    }
  }


  function refreshBankRunningList() {
    Object.assign(bankRunningList, {sumskje: '0.00', optionList: [], sumfkje: '0.00'});
  }

  function refreshBankBalanceList() {
    Object.assign(bankBalanceList, {sumskje: '0.00', optionList: [], sumfkje: '0.00'});
  }

  /**
   * 银行流水 注册弹出编辑窗口
   * 作者：qdl
   * 日期：2022-06-28
   */
  const [registerBankRunning, { openModal: bankRunningModal }] = useModal();

  /**
   * 银行流水 打开添加编辑窗口
   * 作者：qdl
   * 日期：2022-06-28
   */
  function handleBankRunningAdd() {
    let record = Object.assign({}, bankRunningForm);
    bankRunningModal(true, { record, isUpdate: false });
  }

  /**
   * 银行流水 提交触发
   * 作者：qdl
   * 日期：2022-06-28
   */
  function bankRunningOk() {
    loadBankRunnigList('', bankRunningForm.bankId, bankRunningForm.sflx, bankRunningForm.jzsj, bankRunningForm.je);
  }

  /**
   * 银行流水 注册弹出编辑窗口
   * 作者：qdl
   * 日期：2022-06-28
   */
  const [registerAccountFlowPay, { openModal: accountFlowPayModal }] = useModal();

  function flowPayModal() {
    var list = accountList.optionList;
    var je = 0;
    var sflx = bean.sflx;
    if (sflx == '1') {
      je = bean.skje;
    } else {
      je = bean.fkje;
    }
    var dwmc = '';
    if (list != null && list.length > 0) {
      dwmc = list[0].sfmc;
    }
    var record = {
      dwmc: dwmc,
      je: je || 0,
      bankId: bankRunningForm.bankId || '',
      jzsj: moment().format('YYYY-MM-DD'),
    };

    accountFlowPayModal(true, { record });
  }

  /**
   * 支付 提交触发
   * 作者：qdl
   * 日期：2022-06-28
   */
  function flowPayFinaceOk(data) {
    bankRunningForm.bankId = data.bankId;
    bankRunningForm.je = data.je;
    bankRunningForm.jzsj = data.jzsj;
    handleCollateRecord();
  }

  // Cancel event
  function onClose() {
    //console.info("isReload.value@@@@@@@@", isReload.value)
    if (isReload.value) {
      emit('success');
    }
  }

  function toNumber(v) {
    let n = 0;
    if (v) {
      n = v;
    }
    return Number(n).toFixed(2);
  }

  //收支项目 - 例表 - 状态样式
function accStatClass(stat) {
  var statClass = "";
  if (stat == "3") {
    statClass = "text-red-500"; //已审核
  } else if (stat == "9") {
    statClass = "text-green-500";
  } else {
    statClass = "";
  }
  return statClass;
}

</script>
<style lang="less" scoped></style>
